import BaseForm, {
  BaseFormSelect,
  BaseFormTextArea,
  BaseModalForm,
  ProFormDateTimePicker,
  ProFormInstance
} from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import BaseTree from '@/components/base/BaseTree';
import { RadarTreeTypeEnum } from '@/pages/radar/data';
import { getList as getRadarList, getRadarTreeListByRadarId } from '@/pages/radar/RadarInfo/api';
import { range } from '@/utils/array';
import { isEmpty } from '@/utils/is';
import { useRequest } from '@/utils/request';
import { useMount } from 'ahooks';
import { Alert, Col, Row, Spin } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import { FaultProcessStateEnum, FaultRecordModel, FaultSourceEnum } from '../../data';
import { addInfo, editInfo } from '../api';

const InfoModal: ModalFC<{ data?: FaultRecordModel }> = (props) => {
  const { data = {} as FaultRecordModel, onSuccess, ...anyProps } = props;
  const { id, structureId = '', raEquipmentIds = '', raEquipmentNames } = data;
  const isadd = isEmpty(id);
  const [radarId, setRadarId] = useState(() => raEquipmentIds.split('-').shift());
  const formRef = useRef<ProFormInstance>();
  const [key, setKey] = useState(() => structureId ?? '');
  const radarTree = useRequest(getRadarTreeListByRadarId, {
    manual: true
  });
  useMount(() => {
    if (radarId) {
      radarTree.run(radarId);
    }
  });
  return (
    <BaseModalForm<FaultRecordModel>
      title='故障记录信息'
      formRef={formRef}
      labelCol={{ style: { width: 80 } }}
      width={840}
      initialValues={{ ...data, radarId }}
      {...anyProps}
      onFinish={async (values) => {
        values.id = id;
        values.isDeal = FaultProcessStateEnum.enum.not;
        values.structureId = key;
        values.faultResource = FaultSourceEnum.enum.manual;
        const { ok, data } = await (isadd ? addInfo : editInfo)(values);
        ok && onSuccess && onSuccess(isadd && values.isDeal ? data : undefined);
        return ok;
      }}
    >
      <Row gutter={16}>
        <Col span={12}>
          <BaseFormSelect
            label='故障雷达'
            name='radarId'
            readonly={!isadd}
            request={getRadarList}
            fieldProps={{
              onChange: (v) => {
                if (v) {
                  radarTree.run(v);
                  setRadarId(v);
                }
              },
              fieldNames: { label: 'name', value: 'id' },
              defaultSelectedOptions: [{ name: raEquipmentNames?.split('-').shift(), id: radarId }]
            }}
            placeholder='请选择故障雷达'
            rules={[{ required: true, message: '请选择故障雷达' }]}
          />
          {radarId === '' ? (
            <Alert type='warning' message='请先选择故障雷达' />
          ) : (
            <BaseForm.Item
              label='雷达结构'
              name='structureId'
              rules={[{ required: true, message: '请选择雷达故障结构' }]}
            >
              <Spin spinning={radarTree.loading}>
                <BaseTree
                  blockNode
                  defaultExpandAll
                  treeData={radarTree.data}
                  bindProps={{ title: 'name', value: 'treeId', key: 'treeId' }}
                  height={320}
                  selectedKeys={[key]}
                  onSelect={([selectedKey]) => {
                    setKey(selectedKey as string);
                    const value = formRef.current?.getFieldsValue(true);
                    formRef.current?.setFieldsValue({ ...value, structureId: selectedKey });
                  }}
                  titleRender={(nodedata) => {
                    return (
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span>{nodedata.title}</span>
                        <span>{RadarTreeTypeEnum.getLabelByValue(nodedata.type)}</span>
                      </div>
                    );
                  }}
                />
              </Spin>
            </BaseForm.Item>
          )}
        </Col>
        <Col span={12}>
          <ProFormDateTimePicker
            label='故障时间'
            name='downTime'
            fieldProps={{
              format: 'yyyy-MM-DD HH:mm:ss',
              disabledDate: (current) => {
                return current && current > moment().endOf('day');
              },
              disabledTime: (current) => {
                const hour = moment().format('HH');
                const min = moment().format('mm');
                const currentHour = current?.format('HH');
                return {
                  disabledHours: () => range(24).splice(Number(hour) + 1, 24),
                  disabledMinutes: () =>
                    currentHour === hour ? range(60).splice(Number(min) + 1, 60) : []
                };
              }
            }}
            rules={[{ required: true, message: '请选择设备故障时间' }]}
          />
          {/* <ProFormRadio.Group
            label='处理状态'
            name='isDeal'
            radioType='button'
            rules={[{ required: true, message: '请选择故障处理状态' }]}
            options={FaultProcessStateEnum.list}
          /> */}
          <BaseFormTextArea label='故障描述' name='remarks' />
        </Col>
      </Row>
    </BaseModalForm>
  );
};

export default InfoModal;
